///////////////////////////////////////
//////   Map Related Functions   //////
///////////////////////////////////////

/////////////////////////
//////   Globals   //////
/////////////////////////

var map;
var geocoder;
var centerChangedLast;
var reverseGeocodedLast;
var currentReverseGeocodeResponse;
var crosshairShape = {coords:[0,0,0,0],type:'rect'};
var currentInfoBubble;
var infoWindow;
var infoWindowMarker;
var markerCluster;
// html containers for side bar use 
var msg_bar_html = "";
var my_msg_bar_html = "";
var event_bar_html = "";
var my_event_bar_html = "";
var my_reg_bar_html = "";
var src_bar_html = "";
// arrays to hold the markers 
var msgMarkers = [];
var myMsgs =[];
var eventMarkers = [];
var myEvents =[];
var myRegMarkers=[];
var srcMarkers = [];
var reopenFunc = undefined;
var _defaultTab = undefined;
var CON_TAB = 4;
var EDIT_TAB = 2;
var REG_TAB = 1;

///////////////////////////////////////
//////   Map Geo Autocomplete   ///////
///////////////////////////////////////

$().ready(function() {
	$('#location').geo_autocomplete(new google.maps.Geocoder, {
		mapkey: 'ABQIAAAAbnvDoAoYOSW2iqoXiGTpYBTIx7cuHpcaq3fYV4NM0BaZl8OxDxS9pQpgJkMv0RxjVl6cDGhDNERjaQ', 
		selectFirst: false,
		minChars: 3,
		cacheLength: 50,
		width: 300,
		scroll: true,
		scrollHeight: 330
	}).result(function(_event, _data) {
		if (_data) map.fitBounds(_data.geometry.viewport);
	});
});

////////////////////////////////
//////     Manage Map     //////
////////////////////////////////

function initialize() {
	var latlng = new google.maps.LatLng(32.049975637218985, 34.81020566406257);
	var myOptions = {
			zoom: 7,
			center: latlng,
			mapTypeId: google.maps.MapTypeId.ROADMAP,
			draggableCursor:'crosshair'
	};
	map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
	geocoder = new google.maps.Geocoder();
	
	var center = new google.maps.Marker({
		map: map,
	   	icon: 'img/crosshair.gif',
	   	shape: crosshairShape
	});
	
	center.bindTo('position', map, 'center');
   
	//create a global infoWindow for search results
	infoWindow = new google.maps.InfoWindow({
		disableAutoPan: false
	});

	//create the global markerClusterer
	markerCluster = new MarkerClusterer(map);
	
	
	setupEvents();
	addMine();
}

function setupEvents() {
	   reverseGeocodedLast = new Date();
	   centerChangedLast = new Date(new Date().getTime() - 2000);
	
	   setInterval(function() {
	     if((new Date()).getSeconds() - centerChangedLast.getSeconds() > 1) {
	       if(reverseGeocodedLast.getTime() < centerChangedLast.getTime())
	         reverseGeocode();
	     }
	   }, 1000);
	
	   google.maps.event.addListener(map, 'zoom_changed', function() {
	     document.getElementById("zoom_level").innerHTML = map.getZoom();
	   });
	
	   google.maps.event.addListener(map, 'idle', centerChanged);
	 }

function getCenterLatLngText() {
	   return '(' + map.getCenter().lat() +', '+ map.getCenter().lng() +')';
	 }
	
function centerChanged() {
	var now = new Date();
	if (centerChangedLast !== undefined && now.getTime() - centerChangedLast.getTime() < 1500) {
		return;
	}
   centerChangedLast = new Date();
   var latlng = getCenterLatLngText();
   document.getElementById('latlng').innerHTML = latlng;
   document.getElementById('formatedAddress').innerHTML = '';
   currentReverseGeocodeResponse = null;
   addFromDB();
 }
	
function reverseGeocode() {
   reverseGeocodedLast = new Date();
   geocoder.geocode({latLng:map.getCenter()},reverseGeocodeResult);
}
	
function reverseGeocodeResult(results, status) {
   currentReverseGeocodeResponse = results;
   if(status == 'OK') {
     if(results.length == 0) {
       document.getElementById('formatedAddress').innerHTML = 'None';
     } else {
       document.getElementById('formatedAddress').innerHTML = results[0].formatted_address;
     }
   } else {
     document.getElementById('formatedAddress').innerHTML = 'Error';
   }
 }
	
	
function geocode() {
   var address = document.getElementById("address").value;
   geocoder.geocode({
     'address': address,
     'partialmatch': true}, geocodeResult);
 }
	
function geocodeResult(results, status) {
   if (status == 'OK' && results.length > 0) {
     map.fitBounds(results[0].geometry.viewport);
   } else {
     alert("Geocode was not successful for the following reason: " + status);
   }
 }

///////////////////////////////////////////
//////   General Marker Management   //////
///////////////////////////////////////////

//close the infobubble
function closeBubble(reopen) {
	if (currentInfoBubble !== undefined) {
		currentInfoBubble.close();
		currentInfoBubble.removeTab(0);
		currentInfoBubble.removeTab(0);
		currentInfoBubble.removeTab(0);
		currentInfoBubble.removeTab(0);
		currentInfoBubble.removeTab(0);
      }
}

//add all my information to the side bar
function addMine() {
	my_msg_bar_html = "";
	my_event_bar_html = ""; 
	myMsgs = [];
	myEvents = [];
	addMyRegistrations();
     document.getElementById("my-msg-bar").innerHTML = my_msg_bar_html;
     document.getElementById("my-event-bar").innerHTML = my_event_bar_html;
	 
     var getRequest = '/'+context+'/resources/users/'+myUser+'/events?past='+showPastEvents;
     if (sinceDate > 0) {
	    	getRequest += '&since='+sinceDate;
	     }
     
	$.get(getRequest
		).success(function(data){
			$.each(data, function(index, event) {
				var content = event.content;
				var id = event.id;
				var location = event.location;
				var latlng = new google.maps.LatLng(location.lat,location.long);
				addMyEvent(latlng, id, content);
			});	
		}).error(function(data){
			alert ("Can't retrieve my events! "+data.responseText);
		});
	
	var getRequest = '/'+context+'/resources/users/'+myUser+'/messages';
	if (sinceDate > 0) {
    	getRequest += '?since='+sinceDate;
     }
	
	$.get(getRequest
	).success(function(data){
		$.each(data, function(index, msg) {
			var content = msg.content;
			var id = msg.id;
			var location = msg.location;
			var latlng = new google.maps.LatLng(location.lat,location.long);				
			addMyMsg(latlng, id, content);
		});
	}).error(function(data){
		alert ("Can't retrieve my messages! "+data.responseText);
	});
}

//add event & msg markers from db
function addFromDB() {
	msg_bar_html = "";
	event_bar_html = "";
	markerCluster.clearMarkers();
	msgMarkers = [];
	eventMarkers = [];
     
     document.getElementById("msg-bar").innerHTML = msg_bar_html;
     document.getElementById("event-bar").innerHTML = event_bar_html;
	 
     var bounds = map.getBounds();
     var center = bounds.getCenter();
     var ne = bounds.getNorthEast();
     var sw = bounds.getSouthWest();
     
     var getRequest = '/'+context+'/resources/events/inRadius?'+
		'lat='+center.lat()+'&'+
		'long='+center.lng()+'&'+
		'n='+ne.lng()+'&'+
		's='+sw.lng()+'&'+
		'w='+sw.lat()+'&'+
		'e='+ne.lat()+'&'+
		'past='+showPastEvents;
		
     
     if (sinceDate > 0) {
    	getRequest += '&since='+sinceDate;
     }

	 
	$.get(getRequest
		).success(function(events){
			$.each(events, function(index, event) {
				var content = event.content;
				var id = event.id;
				var location = event.location;
				var latlng = new google.maps.LatLng(location.lat,location.long);
				var poster = event.poster;
				var time = new Date(event.time);
				var addr = location.address;
				var capacity = event.capacity;
				var name = event.name;
				addEvent(id, poster, name, latlng, addr, content, time, capacity);
			});
			}).error(function(events){
			alert ("Can't retrieve events! "+events.responseText);
		});
	
     var getRequest = '/'+context+'/resources/messages/inRadius?'+
		'lat='+center.lat()+'&'+
		'long='+center.lng()+'&'+
		'n='+ne.lng()+'&'+
		's='+sw.lng()+'&'+
		'w='+sw.lat()+'&'+
		'e='+ne.lat()+'&'+
		'past='+showPastEvents;
		
     
     if (sinceDate > 0) {
    	getRequest += '&since='+sinceDate;
     }
	
	$.get(getRequest
	).success(function(msgs){
		$.each(msgs, function(index, msg) {
			var content = msg.content;
			var id = msg.id;
			var location = msg.location;
			var latlng = new google.maps.LatLng(location.lat,location.long);
			var poster = msg.poster;
			var time = new Date(msg.time);
			var addr = location.address;
			var name = msg.name;
			addMsg(id, poster, name, latlng, addr, content, time);
			});
		}).error(function(msgs){
		alert ("Can't retrieve messages! "+msgs.responseText);
	});
 }

////////////////////////////////////////////
//////    Search Related Functions    //////
////////////////////////////////////////////

//add search result to the map
function addSearch(latlng, content, searchType) {
	   var marker = new google.maps.Marker({
	       position: latlng,
	       map: map,
	       zIndex: Math.round(latlng.lat()*-100000)<<5
	   });
	   if (searchType == "Location") {
		   marker.setIcon('img/purple_MarkerS.png');
	   } else if (searchType == "Keywords") {
		   marker.setIcon('img/pink_MarkerS.png');
	   }
	   
	   
	   //build msg body	   
	   var body = '<div id="content">'+
	   				'<h2 style="background-color:#3B5998; font-weight: bold; color:#FFFFFF; text-align: center; padding-top: 15px; padding-bottom: 15px;">'+
	   				searchType+' Search Result </h2>'+
	   				'<h3 style="text-align: center;">Content</h3>'+
	   				'<p>'+content+'</p>'+
				'</div>';


	   google.maps.event.addListener(marker, 'click', function() {
		   infoWindow.setContent(body);
		   infoWindow.open(map,marker);
	   });
	   
	     // save the info we need to use later for the side_bar
	     srcMarkers.push(marker);			     
	 }

//add all search results to the map
function addSearchResults(resultsArray, searchType) {
	var count = 0;
	var tmp_bar_html = "";
	 $.each(resultsArray, function(index1, resultSource) {
		 $.each(resultSource, function(index2, result) {
			 var res = result.split("||");
			 var lat = res[1];
			 var lng = res[0];
			 var content = res[2];
			 var latlng = new google.maps.LatLng(lat, lng);
			 addSearch(latlng, content, searchType);
			 count += 1;
			 tmp_bar_html += '<a href="javascript:myLatLngClick(' + lat + ',' + lng + ')">' + count + '. ' + content + '<\/a><br\/>';
		 });
	 });
	 if (count > 0) {
		 tmp_bar_html = '<br/><span id="search-results">'+searchType+' Search Results:</span><br/>' + tmp_bar_html;
		 src_bar_html += tmp_bar_html;
		 document.getElementById("src-results-bar").innerHTML = src_bar_html;
	 }
	 alert(count+" search results from WS were added to the map");
}

//clear all search results from the map
function clearSearchResults() {
	$.each(srcMarkers, function(index, marker) {
		marker.setMap(null);
	});			
	srcMarkers = [];
	src_bar_html = "";
	document.getElementById("src-results-bar").innerHTML = src_bar_html;
}

////////////////////////////////////////////
//////   Messages Related Functions   //////
////////////////////////////////////////////

//picks up the click and opens the corresponding window
function msgClick(i) {
	google.maps.event.trigger(msgMarkers[i], "click");
}

//move the center to my msg
function myMsgClick(i) {
	map.setCenter(myMsgs[i]);
}

//add my message to the side bar
function addMyMsg(ll, id, content) {
    myMsgs.push(ll);
    my_msg_bar_html = '<a href="javascript:myMsgClick(' + (myMsgs.length-1) + ')">' + id + '. ' + content + '<\/a><br\/>' + my_msg_bar_html;
    document.getElementById("my-msg-bar").innerHTML = my_msg_bar_html;
}

//add a msg from server to the center of the map
function addMsgAtCenter(msgLoc) {
	$.get(
			msgLoc
		).success(function(data){
			var content = data.content;
			var id = data.id;
			var location = data.location;
			var latlng = new google.maps.LatLng(location.lat,location.long);
			var poster = data.poster;
			var time = new Date(data.time);
			var addr = location.address;
			var name = data.name;
			var marker = addMsg(id, poster, name, latlng, addr, content, time);
			addMyMsg(marker.getPosition(), id, content);
			alert("Message posted successfuly!");
		}).error(function(data){
			alert ("Can't get the added msg! "+data.responseText);
		});
 }
 
//add a msg to the map
 function addMsg(id, poster, name, latlng, addr, content, time) {
	   var marker = new google.maps.Marker({
	       position: latlng,
	       map: map,
	       zIndex: Math.round(latlng.lat()*-100000)<<5
	   });
	   if (myUser == poster) {
		   marker.setIcon('img/darkgreen_MarkerM.png');
	   } else {
		   marker.setIcon('img/green_MarkerM.png');
	   }
	   
	   marker.poster = poster;
	   marker.id = id;
	   marker.latlng = latlng;
	   marker.addr = addr;
	   marker.content = content;
	   marker.time = time;
	   marker.name = name;
	   
	   google.maps.event.addListener(marker, 'click', function() {
	          
		   closeBubble();
		   
		   currentInfoBubble = new InfoBubble({
		          maxWidth: 310,
		          maxHeight: 380
		        });
		   
		   //build msg body	   
		   var msgContent = '<div id="content">'+
		   				'<h2 style="background-color:#3B5998; font-weight: bold; color:#FFFFFF; text-align: center; padding-top: 15px; padding-bottom: 15px;">'+
		   				name+"'s Message </h2>"+
		   				'<h3 style="text-align: center;">Content</h3>'+
		   				'<p>'+content+'</p>'+
						'</div>';
						
				var details = '<div id="content">'+
	   				'<h2 style="background-color:#3B5998; font-weight: bold; color:#FFFFFF; text-align: center; padding-top: 15px; padding-bottom: 15px;">'+
	   				'Message Details </h2>'+
	   				'<p>Message id: '+id+'</p>'+
	   				'<h3 style="text-align: center;">Time</h3>'+
	   				'<p>'+time+'</p>'+
	   				'<h3 style="text-align: center;">Location</h3>'+
	   				'<p>'+addr+'</p>'+
					'</div>';
				
				currentInfoBubble.addTab('Content', msgContent);
				currentInfoBubble.addTab('Details', details);
				
				
			if (marker.poster == myUser) {
				var edit = document.createElement('DIV');
				edit.innerHTML = '<div id="content">'+
					   				'<h2 style="background-color:#3B5998; font-weight: bold; color:#FFFFFF; text-align: center; padding-top: 15px; padding-bottom: 15px;">'+
					   				'Edit Message</h2>'+
					   				'<h3 style="text-align: center;">Actions</h3>'+
					   				'<div style="text-align:center;">'+
					   				'<button align="center" onclick="deleteMsg('+marker.id+')">Delete Message</button>'+
					   				'</div>'+
	   							'</div>';
				currentInfoBubble.addTab('Edit', edit);
			} 
				
				
				currentInfoBubble.open(map, marker);
				
				
				google.maps.event.addListener(currentInfoBubble,'closeclick',function(){
				closeBubble();
			});
		   
	   });
	   
	     // save the info we need to use later for the side_bar
	     msgMarkers.push(marker);
	     markerCluster.addMarker(marker);
	     
	     
	     // add a line to the side_bar html
	     msg_bar_html = '<a href="javascript:msgClick(' + (msgMarkers.length-1) + ')">' + id + '. ' + content + '<\/a><br\/>' + msg_bar_html;
	     document.getElementById("msg-bar").innerHTML = msg_bar_html;
	     
	     return marker;
	     
	 }

 //delete a msg
function deleteMsg(id) {
		closeBubble();
		$.delete('/'+context+'/resources/messages/'+id)
		.success(function (data, resultText, result) {
			alert("Message deleted successfully!");
			addMine();
			google.maps.event.trigger(map, "idle");
		}).error(function(data) {
			alert("Cannot delete! "+data.responseText);
		});
	} 

//////////////////////////////////////////
//////   Events Related Functions   //////
//////////////////////////////////////////

//picks the click and open the event
function eventClick(i) {
	google.maps.event.trigger(eventMarkers[i], "click");
}

//picks the click and move the center to the event
function myEventClick(i) {
	map.setCenter(myEvents[i]);
}

//move the center to the latlng
function myLatLngClick(lat,lng) {
	var newCenter = new google.maps.LatLng(lat, lng);
	map.setCenter(newCenter);
}
	

//add my events registrations
function addMyRegistrations() {
	myRegMarkers = [];
	my_reg_bar_html = "";
	
	$.get('/'+context+'/resources/users/'+myUser+'/registrations?past='+showPastEvents
			).success(function(data,status,result) {
				$.each(data, function(index, reg) {
					var id = reg.id;
					var content = reg.content;
					var location = reg.location;
					var lat = location.lat;
					var lng = location.long;
					myRegMarkers[id]=new google.maps.LatLng(lat, lng);
					my_reg_bar_html = '<a href="javascript:myLatLngClick(' + myRegMarkers[id].lat() +','+ myRegMarkers[id].lng() + ')">' + id + '. ' + content + '<\/a><br\/>' + my_reg_bar_html;
				});
				document.getElementById("my-reg-bar").innerHTML = my_reg_bar_html;
			}).error(function(data,status,result) {
				alert("Unable to get my registrations! "+data.responseText);
			});
}

//add my event to the side bar
function addMyEvent(ll, id, content) {
    myEvents.push(ll);
    my_event_bar_html = '<a href="javascript:myEventClick(' + (myEvents.length-1) + ')">' + id + '. ' + content + '<\/a><br\/>' + my_event_bar_html;
    document.getElementById("my-event-bar").innerHTML = my_event_bar_html;
}

//add an event from the server to the center of the map
function addEventAtCenter(eventLoc) {
	$.get(
			eventLoc
		).success(function(data){
			var content = data.content;
			var id = data.id;
			var location = data.location;
			var latlng = new google.maps.LatLng(location.lat,location.long);
			var poster = data.poster;
			var time = new Date(data.time);
			var addr = location.address;
			var capacity = data.capacity;
			var name = data.name;	
			addEvent(id, poster, name, latlng, addr, content, time, capacity);
			addMyEvent(latlng, id, content);
		}).error(function(data){
			alert ("Can't get the added event! "+data.responseText);
		});
 }

//add an event to the map
function addEvent(id, poster, name, latlng, addr, content, time, capacity) {
	   var marker = new google.maps.Marker({
	       position: latlng,
	       map: map,
	       zIndex: Math.round(latlng.lat()*-100000)<<5
	   });
	   if (myUser == poster) {
		   marker.setIcon('img/blue_MarkerE.png');
	   } else {
		   marker.setIcon('img/paleblue_MarkerE.png');
	   }
	   
	   marker.id = id;
	   marker.poster = poster;
	   marker.name = name;
	   marker.latlng = latlng;
	   marker.addr = addr;
	   marker.content = content;
	   marker.time = time;
	   marker.capacity = capacity;	

	   //add click listener
	   google.maps.event.addListener(marker, 'click', function() {
		   reopenFunc = arguments.callee;
	          
		   closeBubble();
		   $.get('/'+context+'/resources/events/'+id+'/registered'
				   ).success(function(data) {

					   currentInfoBubble = new InfoBubble({
					          maxWidth: 310,
					          maxHeight: 380
					        });
				        
				           if (marker.name == myName) {
				        	   marker.status = '<p style="color:blue; text-align:center">You are the CREATOR of this event</p>';
				           } else {
				        	   marker.status = '<p style="text-align:center">You are NOT REGISTERED to this event</p>';
				           }
					   marker.guests = data;
					   var guestNames = '<p>';
					   $.each(marker.guests, function(index, guest) {
						   if (guest.name == myName) {
							   marker.status = '<p style="color:green; text-align:center">You are REGISTERED to this event</p>';
						   }
						   guestNames += guest.name;
						   if (index < (marker.guests.length - 1)) {
							   guestNames += ', ';
						   }
					   });
					   guestNames += '</p>';
					   var status = '<div id="content">'+
						   				'<h2 style="background-color:#3B5998; font-weight: bold; color:#FFFFFF; text-align: center; padding-top: 15px; padding-bottom: 15px;">'+
						   				marker.name+"'s Event </h2>"+
						   				'<p>Event id: '+marker.id+'</p>'+
						   				'<h3 style="text-align: center;">Status</h3>'+
						   				marker.status+
						   				'<h3 style="text-align: center;">Time</h3>'+
						   				'<p>'+marker.time+'</p>'+
						   				'<h3 style="text-align: center;">Location</h3>'+
						   				'<p>'+marker.addr+'</p>'+
						   				'<h3 style="text-align: center;">Capacity</h3>'+
						   				'<p>'+marker.guests.length+'/'+marker.capacity+'</p>'+
						   				'<h3 style="text-align: center;">Actions</h3>'+
						   				'<div style="text-align:center;">'+
						   				'<button align="center" onclick="register('+marker.id+','+marker.latlng.lat()+','+marker.latlng.lng()+',\''+marker.content+'\')">Register</button>'+
						   				'<button onclick="unregister('+marker.id+')">Unregister</button>'+
						   				'</div>'+
		   							'</div>';

						var info = document.createElement('DIV');
						info.innerHTML ='<h2 style="background-color:#3B5998; font-weight: bold; color:#FFFFFF; text-align: center; padding-top: 15px; padding-bottom: 15px;">'+
		   								"Event Information</h2>"+marker.content; 
						   					        				
		   							
				        var guests = document.createElement('DIV');
				    	 guests.innerHTML ='<h2 style="background-color:#3B5998; font-weight: bold; color:#FFFFFF; text-align: center; padding-top: 15px; padding-bottom: 15px;">'+
		   								"Registered Guests</h2>"+ 
				    		 				'<h3>Creator: </h3>'+marker.name+
				        					'<h3>Guests: </h3>'+guestNames;
		   					        				
				        
				currentInfoBubble.addTab('Event Status', status);
				
				if (marker.poster == myUser) {
					var edit = document.createElement('DIV');
					edit.innerHTML = '<div id="content">'+
						   				'<h2 style="background-color:#3B5998; font-weight: bold; color:#FFFFFF; text-align: center; padding-top: 15px; padding-bottom: 15px;">'+
						   				"Edit Event</h2>"+
						   				'<h3 style="text-align: center;">Actions</h3>'+
						   				'<div style="text-align:center;">'+
						   				'<button align="center" onclick="deleteEvent('+marker.id+')">Delete Event</button>'+
						   				'</div>'+
						   				'<h3 style="text-align: center;">Consensuses</h3>'+
						   				'<div style="text-align:center;">'+
						   				'<input class="con_content" type="text" id="con" value=""/>'+
						   				'<button onclick="addCon('+marker.id+')">Add Consensus</button>'+
						   				'</div>'+
		   							'</div>';
					currentInfoBubble.addTab('Edit', edit);
					CON_TAB = 5;
				} else {
					CON_TAB = 4;
				}
				
				currentInfoBubble.addTab('Information', info);
				currentInfoBubble.addTab('Guests', guests);
				
			
				$.get('/'+context+'/resources/events/'+id+'/cons'
						).success(function(data,status,response) {
							var cons = document.createElement('DIV');
   					     	cons.innerHTML = '<h2 style="background-color:#3B5998; font-weight: bold; color:#FFFFFF; text-align: center; padding-top: 15px; padding-bottom: 15px;">'+
													"Event Consensuses</h2>";
							$.each(data, function(index,con) {
								var conId = con.id;
								var conName = con.name;
								var myVote = con.myVote;
								var currStatus = con.currStatus;
								var numVotes = con.numVotes;
								
								var status = '<span>UNDECIDED</span>';
								if (currStatus == true) {
									status = '<span style="color: #009933">APPLIED</span>';
								} else if (currStatus == false) {
									status = '<span style="color: #E60000">NOT APPLIED</span>';
								}
								var vote = ""; 
								if (myVote == true) {
					   				vote = '<p>Your current vote is YES</p>';
								}
					   			if (myVote == false) {
					   				vote = '<p>Your current vote is NO</p>';
					   			}
								cons.innerHTML +=
					   				'<h3 style="text-align: center;">Consensus '+conId+': '+status+' ('+numVotes+' votes)</h3>'+
					   				'<p>'+conName+'</p>'+
					   				'<div style="text-align:center;">'+
					   				vote+
					   				'<button onclick="voteCon('+conId+')">Yes</button>'+
					   				'<button onclick="unvoteCon('+conId+')">No</button>'+
					   				'</div><hr/>';
							});
							currentInfoBubble.addTab('Consensus', cons);
							if (_defaultTab == CON_TAB) {
								currentInfoBubble.setTabActive(CON_TAB);
							}
						}).error(function(data) {
							alert("Can't retrieve consensuses! "+data.responseText);
						});

		
					 currentInfoBubble.open(map, marker);
					 
				google.maps.event.addListener(currentInfoBubble,'closeclick',function(){
					reopenFunc = function() {
						// do nothing, prevents accidental callings of this()
					};
					closeBubble();
				});
		   							
					  // var infowindow = new google.maps.InfoWindow({ content: marker.body });
					   //infowindow.open(map,marker);
				   }).error(function(data) {
					   alert("Can't get event's memebers! "+data.responseText);
				   });
	   });
	     eventMarkers.push(marker);
	     markerCluster.addMarker(marker);
	     
	     event_bar_html = '<a href="javascript:eventClick(' + (eventMarkers.length-1) + ')">' + id + '. ' + content + '<\/a><br\/>' + event_bar_html;
	     document.getElementById("event-bar").innerHTML = event_bar_html;
	 }

//add consensus
function addCon(id) {
	var cons = document.getElementsByClassName("con_content");
	var con = cons[cons.length - 1].value;
	if (con.length == 0) {
		alert("Please enter a name for the consensus");
		return;
	}
	$.post('/'+context+'/resources/events/'+id+'/cons', JSON.stringify({name: con})
			).success(function(data,status,result) {
				alert("Consensus added successfully");
				closeBubble();
				_defaultTab = EDIT_TAB;
				reopenFunc();
			}).error(function(data) {
				alert("Unable to added consensus! "+data.responseText);
			});
}

//vote YES for consensus
function voteCon(id) {
	$.post('/'+context+'/resources/cons/'+id+'/votes',
			JSON.stringify({vote: true})
			).success(function(data) {
				alert("Voted YES");
				closeBubble();
				reopenFunc();
				_defaultTab = CON_TAB;
			}).error(function(data) {
				alert("Unable to vote! "+data.responseText);
			});
}

//vote NO for consensus
function unvoteCon(id) {
	$.post('/'+context+'/resources/cons/'+id+'/votes',
			JSON.stringify({vote: false})
			).success(function(data) {
				alert("Voted NO");
				closeBubble();
				_defaultTab = CON_TAB;
				reopenFunc();
			}).error(function(data) {
				alert("Unable to vote! "+data.responseText);
			});
}

//register to event
function register(id,lat,lng,content) {
  $.post('/'+context+'/resources/events/'+id+'/register')
	.success(function (data, resultText, result) {
		if (result.status == 204) {
			alert("You're already registered...");
		} else {
			alert("You've been successfully registered to the event!");
			myRegMarkers[id]=new google.maps.LatLng(lat, lng);
			my_reg_bar_html = '<a href="javascript:myLatLngClick(' + myRegMarkers[id].lat() +','+ myRegMarkers[id].lng() + ')">' + id + '. ' + content + '<\/a><br\/>' + my_reg_bar_html;
			document.getElementById("my-reg-bar").innerHTML = my_reg_bar_html;
			closeBubble();
			_defaultTab = REG_TAB;
			reopenFunc();
		}
	}).error(function(data) {
		alert("Unable to register! "+data.responseText);
	});
}

//unregister from event
function unregister(id) {
	$.delete('/'+context+'/resources/events/'+id+'/register')
	.success(function (data, resultText, result) {
		if (result.status == 204) {
			alert("You're not registered to this event...");
		} else {
			alert("You've been unregistered from the event...");
			addMyRegistrations();
			closeBubble();
			_defaultTab = REG_TAB;
			reopenFunc();
		}
	}).error(function(data) {
		alert("Unable to unregister! "+data.responseText);
	});
}

//delete an event
function deleteEvent(id) {
	closeBubble();
	$.delete('/'+context+'/resources/events/'+id)
	.success(function (data, resultText, result) {
		alert("Event deleted successfully!");
		addMine();
		google.maps.event.trigger(map, "idle");
	}).error(function(data) {
		alert("Cannot delete! "+data.responseText);
	});
} 

